<!DOCTYPE html>
<html>
<head>
    <title>多摄像头监控系统</title>
    <style>
        .video-container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            padding: 20px;
        }
        .video-box {
            width: 400px;
            border: 1px solid #ccc;
            padding: 10px;
            border-radius: 5px;
        }
        video {
            width: 100%;
            background-color: #000;
        }
        .controls {
            margin: 20px;
        }
        .login-form {
            margin: 20px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
            max-width: 400px;
        }
    </style>
</head>
<body>
    <div class="login-form" id="loginForm">
        <h2>摄像头登录</h2>
        <div>
            <label>设备ID:</label>
            <input type="text" id="deviceId">
        </div>
        <div>
            <label>用户名:</label>
            <input type="text" id="username">
        </div>
        <div>
            <label>密码:</label>
            <input type="password" id="password">
        </div>
        <button onclick="connectToCamera()">连接</button>
    </div>

    <div class="video-container" id="videoContainer"></div>

    <script>
        const configuration = {
            iceServers: [
                { urls: "stun:stun.l.google.com:19302" },
                // 如果需要TURN服务器，添加在这里
                // { urls: "turn:your-turn-server.com", username: "user", credential: "pass" }
            ]
        };
        
        let signalingSocket;
        let peerConnections = {};
        
        function connectToCamera() {
            const deviceId = document.getElementById('deviceId').value;
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            // 连接到信令服务器
            signalingSocket = new WebSocket(`ws://www.v110.cc:8080?type=client&deviceId=${deviceId}&username=${username}&password=${password}`);
            
            signalingSocket.onopen = () => {
                console.log('已连接到信令服务器');
                setupVideoStream(deviceId);
            };
            
            signalingSocket.onerror = (error) => {
                console.error('信令服务器连接错误:', error);
                alert('连接失败，请检查认证信息');
            };
            
            signalingSocket.onmessage = (event) => {
                const message = JSON.parse(event.data);
                const deviceId = message.deviceId;
                
                if (!peerConnections[deviceId]) {
                    console.error('没有找到对应的PeerConnection');
                    return;
                }
                
                if (message.sdp) {
                    peerConnections[deviceId].setRemoteDescription(new RTCSessionDescription(message.sdp))
                        .then(() => {
                            if (message.sdp.type === 'offer') {
                                return peerConnections[deviceId].createAnswer();
                            }
                        })
                        .then(answer => {
                            if (answer) {
                                return peerConnections[deviceId].setLocalDescription(answer);
                            }
                        })
                        .then(() => {
                            signalingSocket.send(JSON.stringify({
                                target: 'device',
                                data: {
                                    deviceId: deviceId,
                                    sdp: peerConnections[deviceId].localDescription
                                }
                            }));
                        })
                        .catch(error => {
                            console.error('处理SDP错误:', error);
                        });
                } else if (message.ice) {
                    peerConnections[deviceId].addIceCandidate(new RTCIceCandidate(message.ice))
                        .catch(error => {
                            console.error('添加ICE候选错误:', error);
                        });
                }
            };
        }
        
        function setupVideoStream(deviceId) {
            // 创建视频元素
            const videoContainer = document.getElementById('videoContainer');
            const videoBox = document.createElement('div');
            videoBox.className = 'video-box';
            videoBox.id = `box-${deviceId}`;
            
            const videoElement = document.createElement('video');
            videoElement.autoplay = true;
            videoElement.controls = true;
            videoElement.id = `video-${deviceId}`;
            
            const deviceLabel = document.createElement('h3');
            deviceLabel.textContent = `设备: ${deviceId}`;
            
            videoBox.appendChild(deviceLabel);
            videoBox.appendChild(videoElement);
            videoContainer.appendChild(videoBox);
            
            // 创建PeerConnection
            const pc = new RTCPeerConnection(configuration);
            peerConnections[deviceId] = pc;
            
            pc.onicecandidate = (event) => {
                if (event.candidate) {
                    signalingSocket.send(JSON.stringify({
                        target: 'device',
                        data: {
                            deviceId: deviceId,
                            ice: event.candidate
                        }
                    }));
                }
            };
            
            pc.ontrack = (event) => {
                const videoElement = document.getElementById(`video-${deviceId}`);
                if (event.streams && event.streams[0]) {
                    videoElement.srcObject = event.streams[0];
                } else {
                    const stream = new MediaStream();
                    stream.addTrack(event.track);
                    videoElement.srcObject = stream;
                }
            };
            
            // 发送offer给设备
            pc.createOffer()
                .then(offer => pc.setLocalDescription(offer))
                .then(() => {
                    signalingSocket.send(JSON.stringify({
                        target: 'device',
                        data: {
                            deviceId: deviceId,
                            sdp: pc.localDescription
                        }
                    }));
                })
                .catch(error => {
                    console.error('创建offer错误:', error);
                });
        }
    </script>
</body>
</html>